#include "order_process_database.h"

Order_Process_Database* Order_Process_Database::m_Instance = nullptr;
QMutex Order_Process_Database::m_mutex;

Order_Process_Database *Order_Process_Database::getInstance(QObject *parent)
{
    // 双重检查锁定，保证线程安全且高效
    if (!m_Instance) {
        QMutexLocker locker(&m_mutex); // 自动加锁/解锁，避免死锁
        if (!m_Instance) {
            m_Instance = new Order_Process_Database(parent);
        }
    }
    return m_Instance;
}

Order_Process_Database::Order_Process_Database(QObject *parent)
    : QObject{parent}
{
    m_SqlPool = SQLitePool::getInstance(this);
}

Order_Process_Database::~Order_Process_Database()
{

}

bool Order_Process_Database::ConnectToDataBase(QSqlDatabase *Db)
{
    if(!Db->open())
    {
        qDebug()<<"Cpp:连接 排料加工数据库 失败 ";
        return false;
    }
    else
    {
        qDebug()<<"Cpp:连接 排料加工数据库 成功 ";
        return true;
    }
}

bool Order_Process_Database::execSql(const QString &sql)
{
    QSqlDatabase* Db = m_SqlPool->get_Order_Process_List_DataBase();
    if(!Db)
    {
        return false;
    }
    if(!Db->isOpen())
    {
        if(!ConnectToDataBase(Db))
            return NULL;
    }

    QSqlQuery query(*Db);

    bool ok = query.exec(sql);
    if(!ok)
    {
        qDebug()<<"Cpp:execSql->lastError():"<<query.lastError();
    }

    return ok;
}

QSqlQuery *Order_Process_Database::execSql_Result(const QString &sql)
{
    QSqlDatabase* Db = m_SqlPool->get_Order_Process_List_DataBase();
    if(!Db)
    {
        return NULL;
    }

    QSqlQuery* query = new QSqlQuery(*Db);
    if(!Db->isOpen())
    {
        if(!ConnectToDataBase(Db))
        {
            return NULL;
        }
    }
    // 查询
    if(query->exec(sql))
    {
        return query;
    }
    else
    {
        qDebug()<<"Cpp:execSql_result->lastError():"<<query->lastError();
    }

    return NULL;
}
